package io.renren.modules.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.customer.bean.CustomerExportBean;
import io.renren.modules.customer.dao.CustomerDao;
import io.renren.modules.customer.entity.CustomerEntity;
import io.renren.modules.customer.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<CustomerEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank((String) params.get("mobilePhone"))) {
            queryWrapper.eq(CustomerEntity::getMobilePhone, ((String) params.get("mobilePhone")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("idNumber"))) {
            queryWrapper.eq(CustomerEntity::getIdNumber, ((String) params.get("idNumber")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("name"))) {
            queryWrapper.eq(CustomerEntity::getName, ((String) params.get("name")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("city"))) {
            queryWrapper.eq(CustomerEntity::getCity, ((String) params.get("city")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("channel"))) {
            queryWrapper.eq(CustomerEntity::getChannel, ((String) params.get("channel")).trim());
        }
        IPage<CustomerEntity> page = this.page(
                new Query<CustomerEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<CustomerEntity> batchUploadCustomerInformation(List<CustomerExportBean> beans, Long currentUserId) {
        if (beans == null || beans.size() < 1) {
            return Collections.emptyList();
        } else {
            //获得已经存在的客户电话号码
            List<String> existedPhones = this.getExistedUserMobilePhones(beans.stream().map(CustomerExportBean::getMobilePhone).map(String::trim).collect(Collectors.toList()));
            LOGGER.debug("已存在的客户电话号码为 {}", String.join(",", existedPhones));

            //将不存在的用户资料存入数据库
            List<CustomerEntity> result = new ArrayList<>();
            Date now = new Date();
            for(CustomerExportBean bean : beans) {
                if (!existedPhones.contains(bean.getMobilePhone().trim())) {
                    LOGGER.debug("客户电话号码 {} 不存在库中，进行插入", bean.getMobilePhone());
                    CustomerEntity entity = new CustomerEntity();
                    entity.setCreateTime(now);
                    entity.setCreateUserId(currentUserId);
                    entity.setMobilePhone(bean.getMobilePhone().trim());
                    entity.setSourceFile(bean.getSourceFile().trim());
                    entity.setName(bean.getName().trim());
                    entity.setArea(bean.getArea().trim());
                    entity.setCity(bean.getCity().trim());
                    entity.setChannel(bean.getChannel().trim());
                    entity.setChannelSource(bean.getChannelSource().trim());
                    entity.setLabel(bean.getLabel().trim());
                    this.baseMapper.insert(entity);
                    result.add(entity);
                }
            }
            return result;
        }
    }

    @Override
    public List<String> getExistedUserMobilePhones(List<String> mobilePhone) {
        if (mobilePhone == null || mobilePhone.size() < 1) {
            return Collections.emptyList();
        } else {
            LambdaQueryWrapper<CustomerEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CustomerEntity::getMobilePhone, mobilePhone);
            List<CustomerEntity> entities = this.baseMapper.selectList(queryWrapper);
            if (entities == null) {
                return Collections.emptyList();
            } else {
                return entities.stream().map(CustomerEntity::getMobilePhone).map(String::trim).collect(Collectors.toList());
            }
        }
    }

    @Override
    public List<CustomerEntity> getCustomersByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        } else {
            LambdaQueryWrapper<CustomerEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CustomerEntity::getId, Stream.of(ids).collect(Collectors.toList()));
            return this.baseMapper.selectList(queryWrapper);
        }
    }

    @Override
    public List<CustomerEntity> getCustomersByMobilePhones(List<String> phones) {
        if (phones == null || phones.size() < 1) {
            return Collections.emptyList();
        } else {
            LambdaQueryWrapper<CustomerEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CustomerEntity::getMobilePhone, phones);
            return this.baseMapper.selectList(queryWrapper);
        }
    }
}